package com.safe.first.domain.user.factory;

import com.safe.first.domain.user.DefaultUser;
import com.safe.first.domain.user.User;
import com.safe.first.domain.user.UserLoginWay;
import com.safe.first.domain.user.repo.UserRepo;
import lombok.AllArgsConstructor;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import java.util.List;

/**
 * @author Mickey
 * @since 2022/6/17
 **/
@Component
@AllArgsConstructor
public class DefaultUserFactory {

    private final UserRepo userRepo;
    private final BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();

    public User instance(UserFactoryParam param) {
        User converter = param.converter();
        DefaultUser defaultUser = (DefaultUser) converter;
        String username = defaultUser.getUsername();
        User user = userRepo.byUsername(username);
        Assert.isNull(user, "重复用户名");
        defaultUser.setPassword("{bcrypt}" + bCryptPasswordEncoder.encode(defaultUser.getPassword()));


        UserLoginWay userLoginWay = new UserLoginWay();
        userLoginWay.setType(0);
        userLoginWay.setUniqueId(username);
        defaultUser.setLoginWay(List.of(userLoginWay));
        return defaultUser;
    }

    public interface UserFactoryParam {

        User converter();

    }
}
